package com.yml.mybatis.gererator.util;

import com.yml.mybatis.gererator.meta.ColumnInfo;
import com.yml.mybatis.gererator.meta.DataSourceInfo;
import com.yml.mybatis.gererator.meta.TableInfo;
import com.yml.mybatis.gererator.service.ITableService;
import com.yml.mybatis.gererator.service.TableFactory;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导出
 *
 * @author YML
 * @since 2023-07-20 09:36
 */
public class ExportUtils {

    public static void exportAllDbInfoToMarkdown(DataSourceInfo dataSource,String path)
            throws Exception {
        System.out.println("正在导出为Markdown文件...");
        dataSource.getConnection();
        if (StringUtils.isBlank(path)){
            path = System.getProperty("user.dir");
        }
        Map<String,Object> dataMap = getData(dataSource);
        Path filePath = Path.of(path + File.separator + dataSource.getDbName() + ".md");
        FreemarkerUtils.createFileFromTemplate(filePath,dataMap,"markdown.ftl");
        System.out.println("Markdown文件导出完成");
    }

    public static void exportAllDbInfoToWord(DataSourceInfo dataSource,String path)
            throws Exception {
        System.out.println("正在导出为Word文件...");
        dataSource.getConnection();
        if (StringUtils.isBlank(path)){
            path = System.getProperty("user.dir");
        }
        Map<String,Object> dataMap = getData(dataSource);
        Path filePath = Path.of(path + File.separator + dataSource.getDbName() + ".doc");
        FreemarkerUtils.createFileFromTemplate(filePath,dataMap,"word.ftl");
        System.out.println("Word文件导出完成");
    }

    private static Map<String,Object> getData(DataSourceInfo dataSource) throws SQLException {
        Map<String,Object> dataMap = new HashMap<>();
        dataSource.getConnection();
        String dbName = dataSource.getDbName();
        dataMap.put("dbName",dbName);
        ITableService service = TableFactory.getService(dataSource);
        List<TableInfo> tableInfos = service.queryAllTables();
        for (TableInfo v : tableInfos) {
            List<ColumnInfo> columnInfos = service.queryColumns(v.getId());
            v.setColumnInfos(columnInfos);
        }
        dataSource.close();
        dataMap.put("tables",tableInfos);
        return dataMap;
    }

    public static void main(String[] args) throws Exception {
//        DataSourceInfo info = new DataSourceInfo(
//                "jdbc:sqlserver://localhost:1433;databaseName=tt;encrypt=false",
//                "sa",
//                "123456");
        DataSourceInfo info = new DataSourceInfo(
                "jdbc:mysql://localhost:3306/ruoyi?allowMultiQueries=true",
                "root",
                "123456");
        ExportUtils.exportAllDbInfoToWord(info,"E://Desktop");
        ExportUtils.exportAllDbInfoToMarkdown(info,"E://Desktop");
    }
}
